// 自定义hooks

import { useEffect, useState } from "react";
import { message, notification } from "antd";
import axios from "axios";

function usePublish(type) {
  const { username } = JSON.parse(localStorage.getItem("token"));
  const [dataSource, setDataSource] = useState([]);
  useEffect(() => {
    axios
      .get(
        `http://localhost:5000/news?author=${username}&publishState=${type}&_expand=category`
      )
      .then((res) => {
        setDataSource(res.data);
      })
      .catch(() => {
        message.error("获取待发布新闻列表失败");
      });
  }, [username, type]);

  const handlePublish = (id) => {
    // console.log(id);
    setDataSource(dataSource.filter((item) => item.id !== id));
    axios
      .patch(`http://localhost:5000/news/${id}`, {
        publishState: 2,
        publishTime: new Date().getTime(),
      })
      .then(() => {
        // 成功后的消息通知
        notification.open({
          message: "通知",
          description: "您可以到【发布管理/已发布】中查看该新闻",
          duration: 4,
          placement: "bottomRight",
        });
      })
      .catch(() => {
        message.error("发布失败");
      });
  };
  const handleSunset = (id) => {
    setDataSource(dataSource.filter((item) => item.id !== id));
    axios
      .patch(`http://localhost:5000/news/${id}`, {
        publishState: 3,
      })
      .then(() => {
        // 成功后的消息通知
        notification.open({
          message: "通知",
          description: "您可以到【发布管理/已下线】中查看该新闻",
          duration: 4,
          placement: "bottomRight",
        });
      })
      .catch(() => {
        message.error("下线失败");
      });
  };
  const handleDelete = (id) => {
    setDataSource(dataSource.filter((item) => item.id !== id));
    axios
      .delete(`http://localhost:5000/news/${id}`)
      .then(() => {
        // 成功后的消息通知
        notification.open({
          message: "通知",
          description: "您已删除该新闻",
          duration: 4,
          placement: "bottomRight",
        });
      })
      .catch(() => {
        message.error("删除失败");
      });
  };

  return { dataSource, handlePublish, handleSunset, handleDelete };
}
export default usePublish;
